<template>
  <div class="unit-select">
    <!-- 选择单位 -->
    <el-cascader
      v-if="selectType == 1"
      v-model="value"
      :options="options"
      :props="props"
      @change="handleChange"
      clearable
      filterable
      style="width: 100%"
    ></el-cascader>
    <el-select
      v-model="value"
      placeholder="请选择"
      v-if="selectType == 2"
      @change="handleChange"
      style="width: 100%"
    >
      <el-option
        v-for="item in options"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      >
      </el-option>
    </el-select>
  </div>
</template>
<script>
// import { tbDeptQuery } from "@/api/admin/user/department-manage.js";
import { openApiSysDeptQuery } from "@/api/openApi";
export default {
  data() {
    return {
      value: "",
      options: [],
      props: {
        children: "childList",
        label: "name",
        value: "id",
        expandTrigger: "hover",
        emitPath: false,
        checkStrictly: true,
      },
    };
  },
  // props: ["defaultValue"],
  props: {
    defaultValue: String,
    selectType: {
      type: Number,
      default: 1,
    },
    //显示层级
    level: {
      type: Number,
      default: 100,
    },
  },
  watch: {
    defaultValue(newVal, oldVal) {
      this.value = newVal;
    },
  },
  mounted() {
    this.getTree();
  },
  methods: {
    getTree() {
      openApiSysDeptQuery({ pId: "0" }).then((res) => {
        this.options = res.data.data;
        this.recursion(this.options);
        if (this.level == 2) {
          this.options.forEach((v) => {
            if (v && v.hasOwnProperty("childList")) {
              v.childList.forEach((m) => {
                if (m && m.hasOwnProperty("childList")) {
                  delete m.childList;
                }
              });
            }
          });
        }
        this.value = this.defaultValue;
      });
    },
    recursion(data) {
      let arr = data.constructor === Array ? data : data.childList;
      arr.forEach((v) => {
        if (!v.childList.length) {
          delete v.childList;
          return;
        }
        this.recursion(v);
      });
    },
    handleChange(value) {
      this.$emit("e-unitData", value);
    },
  },
};
</script>